/**
 * @description: 场景转换器
 * @file: transform-controls.ts
 * @author: Evan
 * @date: 2025.07.17 14:26:17
 * @week: 周四
 * @version: V
 */

import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js'
import { Scene } from '../class'
import * as MD from '../data/methods'

type ST = InstanceType<typeof Scene>

import { modelOpts } from './store'
import { Message } from '@/utils/element'

export function transfControls(core: ST) {
  return {
    add() {
      const camera = core.camera
      const controls = new TransformControls(camera, core.renderer.domElement)

      // 监听相机变化
      controls.addEventListener('dragging-changed', e => {
        core.controls && (core.controls.enabled = !e.value)
      })

      core.transformControls = controls
      core.addObject(controls.getHelper())

      const onKeydown = (e: KeyboardEvent) => this.onKeydown(e)
      window.addEventListener('keydown', onKeydown, false)

      onBeforeUnmount(() => {
        window.removeEventListener('keydown', onKeydown)
      })
    },

    onKeydown(e: KeyboardEvent) {
      console.log(e)
      const control = core.transformControls
      if (!control) return
      switch (e.key) {
        case 'w':
          control.setMode('translate')
          break

        case 'e':
          control.setMode('rotate')
          break

        case 'r':
          control.setMode('scale')
          break

        case '+':
        case '=':
          control.setSize(control.size + 0.1)
          break

        case '-':
        case '_':
          control.setSize(Math.max(control.size - 0.1, 0.1))
          break

        case 'x':
          control.showX = !control.showX
          break

        case 'y':
          control.showY = !control.showY
          break

        case 'z':
          control.showZ = !control.showZ
          break

        case ' ':
          control.enabled = !control.enabled
          break

        case 'Escape':
          control.reset()
          break

        case 'Delete':
          core.modules.mian?.deleteModel({ uuid: modelOpts.uuid })
          break
      }
    },

    // 设置转换对象
    setObject(object: MD.THREE.Object3D) {
      if (object !== core.transformControls?.object) {
        if (!core.setPiece.visible) {
          Message(`当前选中对象名称[${object.name}]`)
        }
        // 转换控制器 设置当前对象
        core.transformControls?.attach(object)
      }
    }
  }
}
